/**
 * Created by Administrator on 15-10-14.
 */
var Delay = (function(){

	function Delay(){
		this.timer = null;
		return this;
	}
	Delay.prototype = {
		set : function(callback,time){
			if(typeof time !== "number") time = 1 * 1000;
			this.clear();
			this.timer = setTimeout(function(){
				callback();
			},time)
		},
		clear : function(){
			clearTimeout(this.timer);
			this.timer = null;
		}
	}
	return Delay;

})();
var Alert = function(type,content,duration,callback){
	var type  = type || "success";
	var duration = duration || 1 * 1000;
	if(!content) return false;
	var wrap = $("#gTopAlertContainer");
	if(!wrap.length){
		wrap = $('<div id="gTopAlertContainer"></div>');
		var styleTxt = '#gTopAlertContainer{ position:fixed; z-index:1000; left:50%; top:-35px; height:35px; padding:0 30px; line-height:35px; font-size:14px; color:#fff; text-align:center; background:#fff;-webkit-box-shadow:1px 1px 2px rgba(0,0,0,.3);box-shadow:1px 1px 2px rgba(0,0,0,.3);}#gTopAlertContainer p{ width:180px;}#gTopAlertContainer.success{ background:#3eba40}#gTopAlertContainer.fail{ background:#df262a}#gTopAlertContainer.error{ background:#df262a}'
		var style = $('<style type="text/css">'+styleTxt+'</style>');
		$("body").append(wrap);
		$("body").append(style);
	}
	wrap.removeClass("success").removeClass("error").removeClass("fail");
	wrap.addClass(type);
	wrap.html(content);
	setTimeout(function(){
		wrap = $("#gTopAlertContainer");
		var width = wrap.outerWidth(true);
		var height = wrap.outerHeight(true);
		wrap.css({"marginLeft":-width/2,"top":-height-2});
		wrap.animate({top:0},"normal",function(){
			var delay = new Delay();
			delay.set(function(){
				wrap.animate({top:-height-2},"normal",function(){
					callback && callback();
				})
			},duration)
		})
	},0)
}
var Pop = {
	show : function(pop){
		pop.addClass("show").show();
		$("#mask").show().css({
			zIndex : 1001,
			opacity : 0.6,
			backgroundColor : "#000"
		})
	},
	hide : function(pop){
		pop.removeClass("hide").hide();
		$("#mask").hide().css({
			zIndex : -1
		})
	}
};
var RichEditor = new Editor();

var Main = RichBase.extend({
	statics : {
		api : "module/pft_resource/api.php",
		queryLinkResource : function(id,opt){
			if(!id) return false;
			var fn = new Function;
			var opt = opt || {};
			var loading = opt.loading || fn;
			var removeLoading = opt.removeLoading || fn;
			var success = opt.success || fn;
			var fail = opt.fail || fn;
			var timeout = opt.timeout || fn;
			var serverError = opt.serverError || fn;
			PFT.Ajax({
				url : "./module/pft_resource/ajax_zax.php",
				type : "post",
				dataType : "json",
				data : {
					action : "single",
					id : id
				},
				loading : function(){ loading()},
				removeLoading : function(){ removeLoading()},
				timeout : function(){ timeout()},
				serverError : function(){ serverError()}
			},function(res){
				if(res){
					success(res);
				}else{
					fail(res);
				}
			})
		}
	},
	EVENTS : {
		"click" : {
			"#submitBtn" : "onSubmitBtnClick",
			"#btnRep" : "openResourcePop"
		}
	},
	init : function(){
		var that = this;
		ImgUploador.init();
		this.reproPop = new ReproResource({container:$("#reproContainer")});
		this.reproPop.on("resource.select",function(data){
			var id = data.id;
			var openBtn = $("#btnRep");
			var data = ReproResource.cache_resource[id];
			if(data) return that.onQueryResourceSuccess(data);
			that.statics.queryLinkResource(id,{
				loading : function(){
					openBtn.addClass("loading").text("资源提取中...");
				},
				removeLoading : function(){
					openBtn.removeClass("loading").text("从资源库进取");
				},
				success : function(res){
					ReproResource.cache_resource[id] = res;
					that.onQueryResourceSuccess(res);
				},
				fail : function(){ alert("请求失败，请稍后重试")},
				timeout : function(){  alert("请求超时，请稍后重试")},
				serverError : function(){ alert("请求出错，请稍后重试")}
			})
		});
		this.formSubmitSuccessDialog = new PFT.Dialog({
			title : "添加成功",
			onBeforeOpen : function(){ console.log("onBeforeOpen")},
			onAfterOpen : function(){ console.log("onAfterOpen")},
			onBeforeClose : function(){ console.log("onBeforeClose")},
			onAfterClose : function(){ console.log("onAfterClose")},
			content : $("#formSubmitSuccessDialogTpl").html(),
			EVENTS : {}
		});

		//如果是编辑状态，把后端给出的缩略图放入ul#uploadImgUl
		var uploadImgUl = $("#uploadImgUl");
		var oimgSrc = uploadImgUl.attr("data-orignimg");
		if(!oimgSrc) return false;
		var html = "";
		if(oimgSrc){
			oimgSrc = oimgSrc.split(",");
			for(var i in oimgSrc){
				html += ImgUploador.parseTemplate({src:oimgSrc[i]});
			}
		}
		uploadImgUl.html(html);

	},
	openResourcePop : function(that,e){
		var btn = $("#btnRep");
		if(btn.hasClass("loading")) return false;
		that.reproPop.show();
	},
	onQueryResourceSuccess : function(data){
		var address = data.address;
		var area = data.area.split("|");
		var prov = area[0];
		var city = area[1];
		var jtype = data.jtype;
		var title = data.title;
		var topic = data.topic;
		var lnglat = data.lng_lat_pos;
		var bhjq = data.bhjq;
		var jtzn = data.jtzn;
		var jqts = data.jqts;
		var jdjj = data.jdjj;
		var imgPath = data.imgpathGrp;
		var p_type = data.p_type;
		var runtime = data.runtime;
		var id = data.id;
		$("#addressInp").val(address);
		$("#provInp").val(prov);
		$("#cityInp").val(city);
		$("#jtypeInp").val(jtype);
		$("#themeInp").val(topic);
		$("#lng_lat_pos_inp").val(lnglat);
		$("#bhjqTarea").val(jqts);
		$("#jtznTarea").val(jtzn);
		$("#runtime").val(runtime);
		$("#linkResourceName").text(title);
		$("#jdjj").html(bhjq);
		RichEditor.setContent(bhjq);
		$("#detailInfoTextarea").val(bhjq);
		var html = "";
		if(imgPath){
			imgPath = imgPath.split(",");
			for(var i in imgPath){
				html += ImgUploador.parseTemplate({src:imgPath[i]});
			}
		}
		$("#uploadImgUl").html(html);
		$("#ptypeHidInp").val(p_type);
		$("#resourceIdHidInp").val(id);
	},
	onSubmitBtnClick : function(that,e){
		e.stopPropagation();
		var form = $("#submitForm");
		var data = form.serialize();
		var btn = $("#submitBtn");
		if(btn.hasClass("loading")) return false;
		$.ajax({
			type:'POST',
			url: "call/jh_prod.php",
			data: data,
			dataType:'json',
			timeout: 30 * 1000,
			beforeSend:function(){
				btn.text("提交中...").addClass("loading");
			},
			success : function(res){
				if(res.status=='ok'){
//					that.formSubmitSuccessDialog.open({
//						title : "保存数据成功",
//						offset : -100
//					})
					alert("保存成功");
					if($("#sidHidInp").val()){ //编辑资源
						window.history.go(-1);
					}else{ //创建新资源
						window.location.href = "product_publish.html?sid="+res.lastid+"&step=2";
					}
				}else{
					alert(res.msg);
				}
				btn.text("提交").removeClass("loading");
			},
			error : function(xhr,text){
				btn.text("提交").removeClass("loading");
				if(text=='timeout'){
					alert("请求已经超时,保存失败");
				}else{
					alert("其他错误,保存失败。");
				}
			}
		})








//		PFT.Ajax({
//			url : that.statics.api,
//			type : "post",
//			dataType : "json",
//			data : data,
//			loading : function(){ btn.addClass("loading").text("提交中..")},
//			removeLoading : function(){ btn.removeClass("loading").text("提交")},
//			timeout : function(){ console.log("提交数据超时")},
//			serverError : function(){ console.log("提交数据服务器出错")}
//		},function(res){
//			var code = res.code;
//			var msg = res.msg || "保存数据失败，请稍后重试";
//			if(code==200){
//				//Alert("success",'<p style="width:160px;"></p>');
//				that.formSubmitSuccessDialog.open({
//					title : "保存数据成功",
//					offset : -100
//				})
//			}else{
//				Alert("fail",'<p style="width:260px;">'+msg+'</p>');
//			}
//		})
	}
});

$(function(){
	new Main({container:$("#mainContainer")})
})